package com.jack.blog.controller;

import com.jack.blog.cache.BlogServiceCache;
import com.jack.blog.cache.CategoryServiceCache;
import com.jack.blog.service.CategoryService;
import com.jack.blog.vo.CategoryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/user/{uid}")
public class BlogCategoryController {
    @Autowired
    private CategoryServiceCache categoryServiceCache;

    @PostMapping("/category")
    public String addCategory(@PathVariable("uid")int uid, CategoryVo categoryVo, Model model){
        String url="/user/"+uid+"/categories";
        try {
            categoryServiceCache.addCategory(uid,categoryVo);
            return "redirect:"+url;
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("error","add error!");
            model.addAttribute("backUrl",url);
            return "error";
        }
    }

    @PostMapping("/category/{cid}/update")
    public String updateCategory(@PathVariable("uid")int uid,@PathVariable("cid")int cid, CategoryVo categoryVo, Model model){
        String url="/user/"+uid+"/categories";
        try {
            categoryServiceCache.updateCategory(cid,uid,categoryVo);
            return "redirect:"+url;
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("error","update error!");
            model.addAttribute("backUrl",url);
            return "error";
        }
    }

    @GetMapping("/category/{cid}/delete")
    public String deleteCategory(@PathVariable("uid")int uid, @PathVariable("cid") int cid, Model model){
        String url="/user/"+uid+"/categories";
        try {
            categoryServiceCache.deleteCategory(uid,cid);
            return "redirect:"+url;
        }catch (IllegalArgumentException i){
            model.addAttribute("error",i.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("error","delete error!");
        }
        model.addAttribute("backUrl",url);
        return "error";
    }
}
